﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace PFMHandlers
{
    class PFMUnZipHandler:PFMHandler
    {
        public override byte[] Perform(PFMCandidate.Candidate aCandidate, byte[] baTarget)
        {
            byte[] result = null;
            base.Perform(aCandidate, baTarget);
            base.GetProcessingData(aCandidate, baTarget);
            try
            {
                MemoryStream ms = new MemoryStream(baTarget);
                ZipEntry theEntry;
                using (ZipInputStream zipStream = new ZipInputStream(ms))
                {
                    while ((theEntry = zipStream.GetNextEntry()) != null)
                    {
                        using (MemoryStream msDes = new MemoryStream())
                        {
                            byte[] data = new byte[2048];
                            int size;
                            while (true)
                            {
                                size = zipStream.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    msDes.Write(data, 0, size);
                                }
                                else { break; }
                            }
                            result = msDes.ToArray();
                        }
                    }
                    zipStream.Close();
                }
            }
            catch
            {
                result = null;
            }
            ChangeCandidateProcessedName(aCandidate);
            return result;
        }
        protected override void ChangeCandidateProcessedName(PFMCandidate.Candidate aCandidate)
        {
            //throw new NotImplementedException();
            //Candidate.ProcessedName = aCandidate.Name;
            base.ChangeCandidateProcessedName(aCandidate);
            if (aCandidate.ProcessedName.EndsWith(".ZIP", StringComparison.CurrentCultureIgnoreCase))
                aCandidate.ProcessedName = aCandidate.ProcessedName.Remove(aCandidate.ProcessedName.Length - 4);
        }
    }
}
